<script setup lang='ts'>
import type { PlusFormGroupRow } from 'plus-pro-components'
import type { VxeGridProps } from 'vxe-table'

import { useOpen } from '@/pages/home/component/use-open'
import { Search } from '@element-plus/icons-vue'
import { useGetManAgreementMetaInfo, useGetManExportAgreementInfo } from '@fl/api/man-api'
import { useAagreementMetaAudit, useEditAgreementMetaInfo, useGetAgreementMetaInfo, useGetExportAgreementInfo } from '@fl/api/purchase'
import { ReasonDialog, SearchForm, SearchTable } from '@fl/components'
import SubmitBtn from '@fl/components/submit-btn.vue'
import { singleFileJsonObj } from '@fl/utils/fn'
import { treeFindLabel } from '@fl/utils/tree'
import { cloneDeep } from 'lodash-es'

import { AGREEMENT_STATE_MAP, AGREEMENT_TYPE, AGREEMENT_TYPE_MAP } from './constant'

const { meta: { isAdmin } } = useRoute()
const { openNewWindow } = useOpen()
const router = useRouter()
const route = useRoute()

// const showReviewForm = ref(false)
const inputProductName = ref<string>('')
const showReason = ref<boolean>(false)
const isReasonDialogLoading = ref<boolean>(false)

const id = computed(() => route.params.id)
const isFromSupplierPages = computed(() => route.path.includes('supplier-pages'))
const isWaitingForSubmit = computed(() => state.value.agreementState === AGREEMENT_STATE_MAP.TO_SUBMIT)
const isWaitingForApprove = computed(() => state.value.agreementState === AGREEMENT_STATE_MAP.TO_APPROVE)
const isProjectContract = computed(() => Number(state.value.agreementType) === AGREEMENT_TYPE_MAP.PROJECT_CONTRACT)
const showApproveBtn = computed(() => !isAdmin && isWaitingForApprove.value && !isFromSupplierPages.value)
const showSubmitBtn = computed(() => !isAdmin && isWaitingForSubmit.value && isFromSupplierPages.value)

const initialState = {} as any
const state = ref(cloneDeep(initialState))

const { data: agreementMetaInfoData, isLoading: isGetAgreementMetaInfoLoading } = isAdmin
    ? useGetManAgreementMetaInfo(id)
    : useGetAgreementMetaInfo(id)
const { isPending: isAgreementMetaAuditPending, mutate: agreementMetaAudit } = useAagreementMetaAudit()
const { isPending: isGetExportAgreementInfoPending, mutate: getExportAgreementInfo } = isAdmin ? useGetManExportAgreementInfo() : useGetExportAgreementInfo()
const { isPending: isEditAgreementMetaInfoPending, mutate: editAgreementMetaInfo } = useEditAgreementMetaInfo()

// #region Form
const formRef = ref()
const isFormLoading = computed(() => isGetAgreementMetaInfoLoading.value)

const group: PlusFormGroupRow[] = [
    {
        columns: [
            {
                colProps: {
                    span: 6,
                },
                label: '协议开始时间',
                prop: 'startDate',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 6,
                },
                label: '协议结束时间',
                prop: 'endDate',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 6,
                },
                label: '协议类目',
                prop: 'categoryName',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 6,
                },
                label: '协议类型',
                prop: 'agreementType',
            },
            {
                colProps: {
                    span: 6,
                },
                label: '甲方',
                prop: 'partyA',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 6,
                },
                label: '乙方',
                prop: 'partyB',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 12,
                },
                label: '协议附件',
                prop: 'agreementAttachment',
            },
            {
                colProps: {
                    span: 12,
                },
                hideInForm: computed(() => !isProjectContract.value),
                label: '关联协议',
                prop: 'relationAgreementName',
                valueType: 'text',
            },
        ],
        title: '基本信息',
    },
    {
        columns: [
            {
                colProps: {
                    span: 24,
                },
                label: '合同金额',
                prop: 'contractPrice',
                renderField: (value: any) => `${value || 0}元`,
                valueType: 'text',
            },
        ],
        hideInGroup: computed(() => !isProjectContract.value),
        title: '金额信息',
    },
    {
        columns: [
            {
                colProps: {
                    span: 24,
                },
                hasLabel: false,
                prop: 'productList',
            },
        ],
        title: '协议产品',
    },
]
// #endregion

// #region Table
const gridOptions = computed<VxeGridProps>(() => ({
    columns: [
        { field: 'productCode', title: '产品编码', width: 200 },
        { field: 'productName', title: '产品名称' },
        { field: 'skuName', title: '商品名称' },
        { field: 'brand', title: '品牌' },
        { field: 'model', title: '型号' },
        { field: 'unit', title: '单位' },
        { field: 'oldPrice', formatter: formatPrice, title: '协议价格', visible: isProjectContract.value, width: 100 },
        { field: 'sellingPrice', formatter: formatPrice, title: '价格(不含税)' },
        { field: 'agreementPrice', formatter: formatPrice, title: '价格(含税)' },
        { field: 'count', title: '数量', visible: isProjectContract.value },
        { slots: { default: 'operate' }, title: '操作' },
    ],
    height: 300,
}))

function formatPrice({ cellValue }) {
    return (!cellValue || Number.isNaN(cellValue)) ? '' : `¥${cellValue.toFixed(2)}元`
}
// #endregion

// #region UI Listener
function onExportBtnClick() {
    getExportAgreementInfo(String(id.value), {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

function onCheckDetailBtnClick(row: any) {
    if (row?.productObject) {
        window.sessionStorage.setItem('PRODUCT_DETAIL', row.productObject)

        // 采购商预览产品详情路由
        let path = '/purchase-pages/purchase-order-management/purchase-product-preview'
        if (isFromSupplierPages.value) {
            // 供应商预览产品详情路由
            path = '/supplier-pages/order-management/supplier-product-preview'
        }

        // 运营端打开预览路由
        if (isAdmin) {
            path = '/operations-pages/strategic-agreement/product-preview'
        }

        router.push(path)
    }
    else {
        openNewWindow('/product-info', {
            id: row.productCode,
        })
    }
}

function onSearchBtnClick() {
    const data = cloneDeep(agreementMetaInfoData.value)
    state.value.agreementProductVOList = inputProductName.value
        ? data.agreementProductVOList.filter((item: any) => item.productName.includes(inputProductName.value))
        : data.agreementProductVOList
}

function onBackBtnClick() {
    router.back()
}

function onRejectBtnClick() {
    showReason.value = true
}

function onPassBtnClick() {
    // showReviewForm.value = true
    agreementMetaAudit({
        id: String(id.value),
        status: 1,
    }, {
        onSuccess: () => {
            ElMessage.success('操作成功')
            router.back()
        },
    })
}

function onSubmitBtnClick() {
    editAgreementMetaInfo({
        ...state.value,
        agreementState: 2,
        productList: state.value.agreementProductVOList,
    }, {
        onSuccess: () => {
            ElMessage.success('操作成功')
            router.back()
        },
    })
}

function onInputReasonConfirm(value: { reason: string }) {
    agreementMetaAudit({
        id: String(id.value),
        remark: value.reason,
        status: 2,
    }, {
        onError: () => {
            isReasonDialogLoading.value = false
        },
        onSuccess: () => {
            isReasonDialogLoading.value = false
            ElMessage.success('操作成功')
            router.back()
        },
    })
}

function showFile(file: any) {
    if (file)
        window.open(file)
}
// #endregion

watchEffect(() => {
    state.value = cloneDeep(agreementMetaInfoData.value)
})
</script>

<template>
    <el-skeleton v-if="isFormLoading" />

    <template v-else>
        <el-card class="mb-20">
            <div class="text-[18px] font-bold leading-[38px]">
                {{ state.agreementName }}
            </div>

            <el-button type="primary"
                       :loading="isGetExportAgreementInfoPending"
                       @click="onExportBtnClick"
            >
                导出明细
            </el-button>
        </el-card>

        <SearchForm ref="formRef"
                    v-model="state"
                    :group="group"
                    :label-width="100"
                    :row-props="{ gutter: 40 }"
        >
            <template #plus-field-agreementType>
                {{ treeFindLabel({ targetValue: state.agreementType, treeData: AGREEMENT_TYPE }) }}
            </template>

            <template #plus-field-contractPrice>
                {{ state?.contractPrice ? `${state?.contractPrice}元` : '' }}
            </template>

            <template #plus-field-agreementAttachment>
                <span class="text-#409EFF truncate cursor-pointer"
                      @click="showFile(singleFileJsonObj(state.agreementAttachment).url)"
                >
                    {{ singleFileJsonObj(state.agreementAttachment).name }}
                </span>
            </template>

            <template #plus-field-productList>
                <div class="w-full">
                    <SearchTable v-bind="gridOptions"
                                 :data="state.agreementProductVOList"
                    >
                        <template #toolbar_buttons>
                            <div class="mb-12 flex w-full justify-end">
                                <el-input v-model="inputProductName"
                                          class="!w-300"
                                          placeholder="请输入产品名称进行搜索"
                                >
                                    <template #append>
                                        <SubmitBtn :icon="Search"
                                                   style="background: #da0004; color:#fff"
                                                   class="w-40 !pl-12"
                                                   @click="onSearchBtnClick"
                                        />
                                    </template>
                                </el-input>
                            </div>
                        </template>

                        <template #operate="{ row }">
                            <span class="text-#409EFF cursor-pointer"
                                  @click="onCheckDetailBtnClick(row)"
                            >
                                查看
                            </span>
                        </template>
                    </SearchTable>
                </div>
            </template>

            <template #footer>
                <div class="mx-auto">
                    <el-button @click="onBackBtnClick">
                        返回
                    </el-button>

                    <template v-if="showApproveBtn">
                        <el-button type="primary"
                                   @click="onPassBtnClick"
                        >
                            通过
                        </el-button>

                        <el-button :loading="isAgreementMetaAuditPending"
                                   @click="onRejectBtnClick"
                        >
                            驳回
                        </el-button>
                    </template>

                    <el-button v-if="showSubmitBtn"
                               type="primary"
                               :loading="isEditAgreementMetaInfoPending"
                               @click="onSubmitBtnClick"
                    >
                        提交
                    </el-button>
                </div>
            </template>
        </SearchForm>
    </template>

    <ReasonDialog v-model:visible="showReason"
                  v-model:loading="isReasonDialogLoading"
                  title="驳回协议"
                  mode="input"
                  @confirm="onInputReasonConfirm"
    />
</template>
